<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\AuthenticationException;

class AuthUserStatus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param null $guard
     * @return mixed
     * @throws AuthenticationException
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $user = $request->user($guard);
        if (empty($user)) {
            throw new AuthenticationException(trans('auth.expired'));
        } else if ($user->is_effect == 0) {
            throw new AuthenticationException(trans('auth.forbidden'));
        } else if ($user->hasRole('agent')) {
            if ($user->extension->audit_status != 'approved') {
                throw new AuthenticationException(trans('auth.audit_failed'));
            }
        }

        return $next($request);
    }
}
